package com.sharein.posting.actions;

import java.io.IOException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.sharein.auth.actions.Action;
import com.sharein.auth.beans.User;
import com.sharein.auth.business.UserManager;

public class Signout implements Action {

	@Override
	public boolean execute(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		User user = UserManager.getSignedInUser(request);
		if(user != null) {
			String shareinID = user.getShareinID();
			Cookie userCookie = null;
			Cookie[] cookies = request.getCookies();
			if(cookies != null) {
				for (Cookie cookie : cookies) {
					if(cookie.getName().equals("shareinID")){
						userCookie = cookie;
						break;
					}
				}
			}
			if(userCookie != null) {
				userCookie.setMaxAge(0);
				response.addCookie(userCookie);
			}
			else {
				HttpSession session = request.getSession();
				session.removeAttribute("shareinID");
			}
			UserManager.setUserSignedIn(shareinID, false);
		}
		response.sendRedirect("authentification.html");
		return true;
	}

}
